﻿using System;
using System.Linq;
using System.Web.Http;
using System.Web.Script.Serialization;
using Medora.Model.Persons;
using Medora.Services.Persons;

namespace MvcApp.Controllers
{
    [RoutePrefix("api/Persons")]
    public class PersonsController : ControllerBase<Person, PersonFilter> {

        private readonly IPersonsService _service;

        public PersonsController(IPersonsService service)
            : base(service)
        {
            _service = service;
        }

        [Route("GetByFilter")]
        public IHttpActionResult GetByFilter(string filter, string ss)
        {
            var serializer = new JavaScriptSerializer();
            var f = serializer.Deserialize<PersonFilter>(filter);
            var result=_service.Get(f)
                .Select(
                    o =>
                        new PersonView
                        {
                            Id = o.Id,
                            Idnp = o.Idnp,
                            FullName = o.FullName,
                            DateBirth = o.DateBirth,
                            Address = o.AddressShort,
                            Sex = o.Sex
                        }).ToList();
            return Ok(result);
        }

         [Route("GetById")]
        public IHttpActionResult GetById(Guid id)
        {
            var person=_service.GetById(id);
            if(person!=null)
            {
                return Ok(new PersonView
                {
                    Idnp = person.Idnp,
                    Id = person.Id,
                    FullName = person.FullName,
                    DateBirth = person.DateBirth,
                    Sex = person.Sex,
                    Address = person.AddressShort,
                    Sector = "Will be Sector"
                });
            }
            return BadRequest("PersonNotExists");
        }
    }

    public class PersonView
    {
        public Guid Id { get; set; }
        
        public string Idnp { get; set; }

        public string FullName { get; set; }

        public DateTime? DateBirth { get; set; }

        public int Sex { get; set; }

        public string Sector { get; set; }

        public string Address { get; set; }
    }
}